<template>
  <div class="main-box">
    <TreeFilter
      title="设备列表"
      id="did"
      label="name"
      :data="deviceListForTree"
      :default-value="treeFilterValues.did"
      @change="changeTreeFilter"
    ></TreeFilter>

    <div class="table-box">
      <div class="card mb10 pt0 pb0" style="display: flex; justify-content: space-between;">
        <el-button type="primary">历史数据</el-button>
        <!-- <featureSelector></featureSelector> -->
        <div id="app">
          <el-button type="primary" @click=openDiaglog>设置发送时间点</el-button>

        </div>
        <el-button type="primary" >{{ faultType }}</el-button>

        <el-button type="primary">{{ currentDate }}</el-button>

      </div>
      <el-dialog v-model="dialogVisible" title="输入信息">
        <el-form :model="form">
          <el-form-item label="故障类型">
            <el-select v-model="form.faultType" placeholder="请选择故障类型" @change="updateTime">
              <el-option
                v-for="item in faultTypes"
                :key="item.value"
                :label="item.label"
                :value="item.value">
              </el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="时间(s)">
            <el-input v-model="form.time" type="number"></el-input>
          </el-form-item>
        </el-form>
        <span slot="footer" class="dialog-footer">
        <el-button @click=openDiaglog>取消</el-button>
        <el-button type="primary" @click="save">保存</el-button>
      </span>
      </el-dialog>

      <LineChart :data="deviceSelect" :xdata="realTimeArray" :features="dataCenter.features"></LineChart>
      <UserDrawer ref="drawerRef" />
      <ImportExcel ref="dialogRef" />
    </div>
  </div>
</template>
<script setup lang="ts" name="dataCenter">
import { ref, reactive, onMounted, watch, toRefs, computed } from "vue";
//组件
import { ElMessage } from "element-plus";
import TreeFilter from "@/components/TreeFilter/index.vue";
import ImportExcel from "@/components/ImportExcel/index.vue";
import UserDrawer from "@/views/proTable/components/UserDrawer.vue";
import { getUserRole } from "@/api/modules/user";
import LineChart from "./components/lineChart.vue";
import featureSelector from "./components/featureSelector.vue";
//api
import {getDeviceList, getFeatureList, getSendTime} from "@/api/modules/new";
//other
import { InitData, DataCenter, FeatureData } from "./inetrfaces";

const dialogVisible = ref(false);
const form = reactive({
  faultType: '',
  time: 0
});

interface FaultType {
  value: string;
  label: string;
  time: number;
}

const faultTypes: FaultType[] = [
  { value: '167', label: '模拟网络盘配线端子混', time: 12342 },
  { value: '172', label: '发送端电缆接地', time: 24684 },
  // { value: '181', label: '断轨', time: 39726 },
  // { value: '188', label: '接收室外端匹配变压器故障', time: 52968 },
  { value: '195', label: '模拟网络盘配线假焊', time: 66210 },
  // { value: '321', label: '室内送端软线开路', time: 79452 },
  // { value: '322', label: '分线盘至电缆盒的电缆不良', time: 86300 }
];
const openDiaglog=async ()=>{
  if (dialogVisible.value===true){
    dialogVisible.value=false
  }else{
    dialogVisible.value=true

  }
}
const updateTime =async () => {
  const selectedFault = faultTypes.find(fault => fault.value === form.faultType);
  if (selectedFault) {
    form.time = selectedFault.time;
  } else {
    form.time = 0;
  }
};
const faultType=ref('')
const save = async () => {

  getSendTime(form.time).then(res => {
      if (res.code==200){
        ElMessage.success("设置成功");
      }else {
        ElMessage.error("失败");
      }
  });
  resetForm()
  dialogVisible.value = false;
};

const resetForm = () => {
  form.faultType = '';
  form.time = 0;
};
const stepLimit = 400;
// let dataHouse: { [key: string]: number[][] } = reactive({});
const dataCenter = reactive<DataCenter>({
  devices: [],
  features: []
});
//远程获取初始化的必要数据
let initDataSuccess = ref(0);
const initDataFlag = 3;
getFeatureList(1).then(res => {
  for (let feature in res) {
    dataCenter.features.push(res[feature]);
  }
  initDataSuccess.value += 1;
});
getFeatureList(2).then(res => {
  for (let feature in res) {
    dataCenter.features.push(res[feature]);
  }
  initDataSuccess.value += 1;
});
getDeviceList().then(res => {
  res.forEach(item => {
    dataCenter.devices.push({
      did: item.did,
      name: item.name,
      mid: item.mid,
      devicePosition: item.devicePosition,
      areaId: item.areaId,
      deviceOnline: false,
      data: [] //[][],行表示特征维度，列表示时间步
    });
  });

  initDataSuccess.value += 1;
});
watch(initDataSuccess, newValue => {
  //当所有远程数据都拿到了之后才标志完成
  if (newValue >= initDataFlag) {
    initDataCenter(); // 远程数据获取完成，初始化DataCenter
  }
});

//记录选中的设备
let selectedIndex = ref(0);
let deviceSelect = ref({});
watch(selectedIndex, newVal => {

  deviceSelect.value = dataCenter.devices[newVal];
});
// 默认 treeFilter 参数
const treeFilterValues = reactive({ did: "1" });
const changeTreeFilter = (val: string) => {
  dataCenter.devices.forEach((device, index) => {
    if (device.did == parseInt(val)) {
      selectedIndex.value = index;
    }
  });
};
// console.log(receivedData);
/**
 * 初始化数据数组
 */
let initDataCenterSuccess = ref(false);
const initDataCenter = () => {
  dataCenter.devices.forEach((device, index) => {
    for (let i = 0; i < dataCenter.features.length; i++) {
      if (dataCenter.features[i].mid == device.mid) {
        dataCenter.devices[index].data.push(new Array(stepLimit).fill(-0.1));
      }
    }
  });
  initDataCenterSuccess.value = true;
  deviceSelect.value = dataCenter.devices[selectedIndex.value];
};

const mqtt_config = {
  topics: { 1: "/analogData", 2: "/25HzanalogData",3:"/currentTime",4:"/status" },
};
import { useGetData } from "./getData.js"; // 导入自定义hook
import { stringify } from "qs";
const { realMessage } = useGetData(mqtt_config); // 使用自定义hook
//初始化数据仓库完成开始接受数据
const updateDataCenter = (data: { topic: any; message: { data: number[][] } }) => {
  if (!initDataCenterSuccess.value) {
    //数据中心未初始化
    return;
  }

  dataCenter.devices.forEach((device, index) => {
    // console.log(device.mid, newValue.topic, mqtt_config.topics[0]);
    if (data.topic != mqtt_config.topics[device.mid]) {
      //如果mid和订阅的不匹配，直接跳过
      return true;
    }
    if (data.message.data.hasOwnProperty(device.did.toString())) {
      let i = 0;
      dataCenter.features.forEach(feature => {
        if (feature.mid == device.mid) {
          if(device.did == 1056 || device.did == 1057 || device.did == 1058) {
            if (i>11){
              dataCenter.devices[index].data=dataCenter.devices[index].data.slice(0, 12);
              return;
            }
          }
          dataCenter.devices[index].data[i].push(data.message.data[device.did][i]); //newValue.message.data[device.did][i] == -0.1 ? null :

          dataCenter.devices[index].data[i].shift();
          i++;
        }
      });



      dataCenter.devices[index].deviceOnline = true;
    } else {
      dataCenter.devices[index].deviceOnline = false;
    }
  });


  updateXData();
};
watch(
  () => realMessage[mqtt_config.topics[1]],
  (newValue, oldValue) => {
    const receivedData = JSON.parse(JSON.stringify(newValue));

    updateDataCenter(receivedData);
  }
);
watch(
  () => realMessage[mqtt_config.topics[2]],
  (newValue, oldValue) => {
    const receivedData = JSON.parse(JSON.stringify(newValue));
    updateDataCenter(receivedData);
  }
);
const currentDate = ref('')
const axisData = ref('')

const pointCount = ref(0);  // 新增计数器，用于记录接收到的数据点数量
watch(
  () => realMessage[mqtt_config.topics[3]],
  (newValue, oldValue) => {
    let seconds = Number(newValue.message);
    currentDate.value= String(seconds);
    const hours = Math.floor(seconds / 3600);
    seconds -= hours * 3600;
    const minutes = Math.floor(seconds / 60);
    seconds -= minutes * 60;


    // axisData.value= `${hours.toString().padStart(2, '0')}:${minutes.toString().padStart(2, '0')}:${seconds.toString().padStart(2, '0')}`;

  }

);

watch(
  () => realMessage[mqtt_config.topics[4]],
  (newValue, oldValue) => {
    faultType.value = newValue.message;
  }

);
//初始化x轴数据
let realTimeArray = reactive([]);
let len = stepLimit;
while (len--) {
  realTimeArray.unshift("");
}

const updateXData = () => {
  let axisData = ''
  pointCount.value += 1;

  if (pointCount.value ==4) {
    const now = new Date();
    const hours = now.getHours().toString().padStart(2, '0');
    const minutes = now.getMinutes().toString().padStart(2, '0');
    const seconds = now.getSeconds().toString().padStart(2, '0');
    axisData = `${hours}:${minutes}:${seconds}`;
    pointCount.value = 0; // 重置计数器
  }
  console.log(pointCount.value)
  console.log(axisData)
  realTimeArray.shift();
  realTimeArray.push(axisData);
};
//设备树形列表相关数据方法
const deviceListForTree = computed(() => {

  const result = [
    { name: "ZPW-2000A", mid: 1, children: [] },
    { name: "25hz", mid: 2, children: [] },
    { name: "ZPW-2000R", mid: 3, children: [] }
  ];

  dataCenter.devices.forEach(device => {
    result[device.mid - 1].children.push({
      name: device.name,
      mid: device.mid,
      did: device.did,
      deviceOnline: device.deviceOnline
    });
  });
  return result;
});





</script>
